package com.dzx.currentency.config;

import com.dzx.currentency.annoations.DataSources;
import com.dzx.currentency.annoations.RoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月21日 17:43:03
 */

@Aspect
@Component
@Slf4j
public class DynamicDataSourceAspect {


    @Before("@annotation(RoutingDataSource)")
    public void beforeSwichDS(JoinPoint point,RoutingDataSource RoutingDataSource) {
        Class<?> className = point.getTarget().getClass();


       String methodName =   point.getSignature().getName();

       Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();

       String  dataSource = DataSourceHolder.DEFAULT_DATASOURCE;

       try{
          Method method =  className.getMethod(methodName,argClass);


          if(method.isAnnotationPresent(RoutingDataSource.class)){

              RoutingDataSource annotation =   method.getAnnotation(RoutingDataSource.class);

              dataSource =   annotation.value();
          }

       }catch (Exception e){

       }

       DataSourceHolder.setDB(dataSource);
    }

    @After("@annotation(RoutingDataSource)")
    public  void afterSwitchDS(JoinPoint point,RoutingDataSource RoutingDataSource){
        DataSourceHolder.clearDB();
    }




}
